package com.youease.chris.util {
	import com.youease.chris.event.TickEvent;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import flash.utils.getTimer;

	/**
	 * Tick
	 *
	 * @author chris
	 *
	 * Dec 15, 2012
	 */
	public class Tick extends Singleton {
		
		private var displayObject:Sprite;//用来提供事件的对象
		private var _timer:Timer;
		private var _delay:int = 40;
		
		private var lastTime:int = 0;
		
		/**
		 * 最大两帧间隔（防止待机后返回卡死） 
		 */
		static public var MAX_INTERVAL:int = 3000;
		
		static public function get instance():Tick {
			return Singleton.getInstanceOrCreate(Tick) as Tick;
		}
		
		public function Tick() {
//			_timer = new Timer(_delay);
//			_timer.addEventListener(TimerEvent.TIMER,onTimer);
//			_timer.start();
			
			displayObject = new Sprite();
			displayObject.addEventListener(Event.ENTER_FRAME,enterFrameHandler);
		}
		
		/**
		 * 重写方法使得默认使用弱引用监听，这样更接近ENTER_FRAME的用法
		 */
		public override function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=true):void
		{
			super.addEventListener(type,listener,useCapture,priority,useWeakReference);
		}
		
		public function pause():void {
			this._timer.stop();
		}
		
		public function start():void {
			this._timer.start();
		}
		
		public function get isRunning():Boolean {
			return _timer && _timer.running;
		}
		
		private function enterFrameHandler(evt:Event):void {
			var nextTime:int = getTimer();
			
			if(lastTime == 0)
				interval = 0;
			else {
				var interval:int = Math.min(nextTime - lastTime,MAX_INTERVAL);
				
				var tickEvent:TickEvent = new TickEvent(TickEvent.TICK);
				tickEvent.interval = interval;//_delay;
				this.dispatchEvent(tickEvent);
			}
			
			lastTime = nextTime;
		}
	}
}